<template>
	<view>
		<view style="width: 100%;height: 400rpx;text-align: center;" @click="chooseImg">
			<view v-if="newsRequest.avatar==null"
				style="width: 100%;height: 100%;background-color: #DCDFE6;display: flex;justify-content: center;align-items: center;">
				点击上传新闻标题</view>
			<img v-else style="width: 100%;height: 100%;width: 96%;margin-top: 2%;" :src="newsRequest.avatar" alt="">
		</view>
		<view style="margin-top: 40rpx;display: flex;justify-content: center;">
			<uni-forms :value="newsRequest" ref="form">
				<uni-forms-item name="title">
					<uni-easyinput type="text" v-model="newsRequest.title" placeholder="请输入新闻标题" />
				</uni-forms-item>
				<uni-forms-item name="content">
					<textarea style="border: 1rpx solid #DCDFE6;" type="text" v-model="newsRequest.content"
						placeholder="请输入新闻内容" :maxlength="250" />
				</uni-forms-item>
				<button @click="addNews" type="primary">发布新闻</button>
			</uni-forms>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				newsRequest: {
					avatar: null,
					orgId: null,
					title: null,
					content: null
				},
				rules: {
					title: {
						rules: [{
							required: true,
							errorMessage: '标题不能为空'
						}]
					},
					content: {
						rules: [{
							required: true,
							errorMessage: '新闻内容不能为空'
						}]
					}
				}
			}
		},
		onReady() {
			// 需要在onReady中设置规则
			this.$refs.form.setRules(this.rules)
		},
		onLoad: function(option) {
			this.newsRequest.orgId = option.orgId
		},
		methods: {
			// 选择图片
			chooseImg() {
				var that = this;
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: function(res) {
						that.newsRequest.avatar = res.tempFilePaths[0];
					}
				});
			},
			// 发布新闻
			addNews() {
				this.$refs.form.submit().then(res => {
					this.$http.request({
						url: '/organizations/web/news/create',
						method: 'POST',
						filePath: this.newsRequest.avatar,
						name: 'avatar',
						formData: {
							orgId: this.newsRequest.orgId,
							title: this.newsRequest.title,
							content: this.newsRequest.content
						},
						type: 'upload'
					}).then(res => {
						res = res.data;
						res = JSON.parse(res);
						if (res.result) {
							uni.showToast({
								title: res.msg
							})
							// 清空数据
							this.newsRequest.avatar = null;
							this.newsRequest.title = null;
							this.newsRequest.content = null;
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							})
						}
					})
				}).catch(err => {
					console.log('表单错误信息：', err);
				})
			}
		}
	}
</script>

<style>
</style>
